/**
 * 解析Excel文件，批量发布物料到中间表
 */
package ext.tianma.part.processors;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import wt.fc.collections.WTArrayList;
import wt.part.WTPart;
import wt.session.SessionServerHelper;
import wt.util.WTException;

import com.ptc.core.components.forms.DefaultObjectFormProcessor;
import com.ptc.core.components.forms.FormResult;
import com.ptc.core.components.util.FeedbackMessage;
import com.ptc.core.ui.resources.FeedbackType;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import ext.com.core.CoreUtil;
import ext.generic.erp.common.CommonUtil;
import ext.generic.erp.service.PartReleaseService;
import ext.tianma.part.imported.ImportedExcelUtil;

public class ReleasePartProcessors extends DefaultObjectFormProcessor{
	private static final String D_VIEW = "Design";
	
	@Override
	public FormResult doOperation( NmCommandBean nmCommandBean , List list )throws WTException {
		FormResult formresult = new FormResult();
    
		HttpServletRequest request = nmCommandBean.getRequest();

		if( request != null ){
			
			 String[] parameter = request.getParameterValues( "fileUrl" );
			 
			 if( parameter == null ){
				 return formresult;
			 }
			 
			 String textName = parameter[0];
			 
			 if( textName != null ){
				 //判断是否为Excel文件类型
				 if( !textName.endsWith(".xls") && !textName.endsWith( ".xlsx" ) ){
					 throw new WTException("选择的文件必须是Excel格式的文件");
				 }
			 }
			
			 File file = (File) request.getAttribute("fileUrl");
			 
			 if( file != null ){				
				 String fileNumber = file.getAbsolutePath(); 
				 
				 if( fileNumber != null ){
					 FileInputStream fis = null;
					 Workbook wb = null;
					 boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
					 try {
						fis = new FileInputStream(fileNumber);
						 //根据Excel文件的格式判断文件的解释方式为03或07（解析Excel兼容性）
						 if( textName.endsWith(".xls") ){
							 wb = new HSSFWorkbook( fis );
						 }else if( textName.endsWith( ".xlsx" ) ){
							 wb = new XSSFWorkbook( fis );
						 }
						//返回系统中不存在的零部件编号
						List< String > strList =new ArrayList<String>();
						 
						releasePartAll( wb , strList );
						
						if( strList != null && strList.size() > 0 ){
							String number = "";							 
							Iterator< String > iterator = strList.iterator();
							while( iterator.hasNext() ){
								if( number.trim().isEmpty() ){
									 number = iterator.next();
								}else{
									number = number + "," + iterator.next();
								}
							}
							String output = "编号："+ number + "在系统中没有找到相关视图对象或指定视图为Design,因此无法发布！";
							
							FeedbackMessage feedbackmessage = new FeedbackMessage(
										FeedbackType.FAILURE, null, output , null, new String[] {});
							formresult.addFeedbackMessage(feedbackmessage);

						}else{
							FeedbackMessage feedbackmessage = new FeedbackMessage(
									FeedbackType.SUCCESS, null, "物料发布成功！" , null, new String[] {});
							formresult.addFeedbackMessage(feedbackmessage);
						}
						 
						
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}finally{
						SessionServerHelper.manager.setAccessEnforced( flag );
					}
				 }
			 }
		}
		
		return formresult;
	}
	
	/**
	 * 解析Excel文件发布对应物料到ERP中
	 * @param fileNumber 目标
	 * @param wb
	 * @param list
	 * @throws WTException
	 */
	private void releasePartAll( Workbook wb , List< String > list ) throws WTException {
		
		//收集需要发布的零部件
		WTArrayList erpList = new WTArrayList();
		
		if( wb != null ){

			Sheet sheet = wb.getSheetAt(0); 
					
			if( sheet != null ){
				for (int i = 1; i < sheet.getLastRowNum()+1; i++) {
					Row row = sheet.getRow( i );
							
					if( row != null ){
						Cell cell0 = row.getCell( 0 );
						Cell cell1 = row.getCell( 1 );
						String number = "";
						String view = "";
						if( cell0 != null ){
							number = ImportedExcelUtil.getCellValueAsString( cell0 , true).trim() ;
						}
									
						if( cell1 != null ){
							view = ImportedExcelUtil.getCellValueAsString( cell1 , true).trim() ;
						}
						
						System.out.println( "Debug   number : " + number + "  view:" + view );
						
						if( ( view != null ) && ( !view.equals( D_VIEW ) ) && number != null ){
							WTPart part = CoreUtil.getWTPartByNumberAndView( number , view );
										
							if( part != null && part.getViewName().trim().equals( view ) ){
								
								if( !erpList.contains( part ) ){
									erpList.add( part );	
								}
																
							}else{
								if( !list.contains( number ) ){
									list.add( number );
								}
							}
							
						}else{
							if( !list.contains( number ) ){
								list.add( number );
							}
						}
					}
				}
				//发布物料到ERP
				if( erpList != null && erpList.size() > 0 ){
					PartReleaseService.releasePersistable( erpList , CommonUtil.getCurrentTime() );
				}
			}
		}
	}
}
